﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;

namespace GlobleSetModule
{
	public partial class LevelsForm : System.Windows.Forms.Form
	{
		public LevelsForm()
		{
			this.InitializeComponent();
		}

		public LevelsForm(CmdLevelSet2 opt)
		{
			this.InitializeComponent();
			this.m_objectReference = opt;
			this.LevelName = new DataGridViewTextBoxColumn();
			this.LevelName.HeaderText = "层名";
			this.LevelName.Width = 80;
			this.LevelElevation = new DataGridViewTextBoxColumn();
			this.LevelElevation.HeaderText = "层高";
			this.LevelElevation.Width = 66;
			this.levelsDataGridView.Columns.AddRange(new DataGridViewColumn[]
			{
				this.LevelName,
				this.LevelElevation
			});
			this.bindingSource1.DataSource = typeof(LevelsDataSource);
			this.levelsDataGridView.AutoGenerateColumns = false;
			this.levelsDataGridView.DataSource = this.bindingSource1;
			this.LevelName.DataPropertyName = "Name";
			this.LevelElevation.DataPropertyName = "Elevation";
			this.bindingSource1.DataSource = this.m_objectReference.SystemLevelsDatum;
			this.m_systemLevelsTotal = this.m_objectReference.SystemLevelsDatum.Count;
			this.m_changedItemsFlag = new int[this.m_systemLevelsTotal];
			this.m_deleteExistLevelIDValue = new int[this.m_systemLevelsTotal];
			this.m_deleteExistLevelTotal = 0;
			this.InitFirstLevelType();
			this.InitStandardLevelType();
			this.levelsDataGridView.CurrentCell = this.levelsDataGridView.Rows[this.levelsDataGridView.RowCount - 1].Cells[0];
			this.ReadAxisData();
		}

		private void addButton_Click(object sender, EventArgs e)
		{
			string name2;
			double elevation2;
			if (this.bindingSource1.Count > 0)
			{
				this.bindingSource1.MoveLast();
				LevelsDataSource levelsDataSource = this.bindingSource1.Current as LevelsDataSource;
				string name = levelsDataSource.Name;
				double elevation = levelsDataSource.Elevation;
				name2 = name + "'";
				double num = (this.textBoxHeight.Text == "") ? 0.0 : Convert.ToDouble(this.textBoxHeight.Text);
				elevation2 = elevation + num;
			}
			else
			{
				name2 = "Level 1";
				elevation2 = 0.0;
			}
			LevelsDataSource levelsDataSource2 = new LevelsDataSource();
			levelsDataSource2.Name = name2;
			levelsDataSource2.Elevation = elevation2;
			this.bindingSource1.Add(levelsDataSource2);
			this.levelsDataGridView.CurrentCell = this.levelsDataGridView.Rows[this.levelsDataGridView.RowCount - 1].Cells[0];
		}

		private void deleteButton_Click(object sender, EventArgs e)
		{
			if (1 == this.levelsDataGridView.RowCount)
			{
				MessageBox.Show("不允许删除唯一的楼层！", "盈建科提示");
				return;
			}
			if (this.bindingSource1.Position > this.m_systemLevelsTotal - 1)
			{
				this.bindingSource1.RemoveCurrent();
				return;
			}
			if (this.bindingSource1.Position <= this.m_systemLevelsTotal - 1 && this.bindingSource1.Position >= 0)
			{
				LevelsDataSource levelsDataSource = this.bindingSource1.Current as LevelsDataSource;
				this.m_deleteExistLevelIDValue[this.m_deleteExistLevelTotal] = levelsDataSource.LevelIDValue;
				this.m_deleteExistLevelTotal++;
				this.bindingSource1.RemoveCurrent();
				this.m_systemLevelsTotal--;
				int[] array = new int[this.m_systemLevelsTotal];
				int i = 0;
				int num = 0;
				while (i < this.m_systemLevelsTotal)
				{
					if (this.bindingSource1.Position == i)
					{
						num++;
					}
					array[i] = this.m_changedItemsFlag[num];
					i++;
					num++;
				}
				this.m_changedItemsFlag = array;
				return;
			}
			if (this.bindingSource1.Position < 0)
			{
				MessageBox.Show("无楼层！", "盈建科提示");
			}
		}

		private void levelsDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
		{
			if (this.levelsDataGridView.CurrentCell.ColumnIndex == 0)
			{
				string text = e.FormattedValue as string;
				char[] array = new char[text.Length];
				array = text.ToCharArray();
				for (int i = 0; i < text.Length; i++)
				{
					if ('\\' == array[i] || ':' == array[i] || '{' == array[i] || '}' == array[i] || '[' == array[i] || ']' == array[i] || '|' == array[i] || ';' == array[i] || '<' == array[i] || '>' == array[i] || '?' == array[i] || '`' == array[i] || '~' == array[i])
					{
						MessageBox.Show("层名中不允许包括以下字符：\r\n\\ : { } [ ] | ; < > ? ` ~ \r\nor any of the non-printable characters.", "盈建科提示");
						e.Cancel = true;
						return;
					}
				}
				string b = this.levelsDataGridView.CurrentCell.FormattedValue as string;
				if (text != b)
				{
					for (int j = 0; j < this.m_objectReference.SystemLevelsDatum.Count; j++)
					{
						if (this.m_objectReference.SystemLevelsDatum[j].Name == text)
						{
							MessageBox.Show("名称重复", "盈建科提示");
							e.Cancel = true;
						}
					}
				}
			}
		}

		private void levelsDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
		{
			MessageBox.Show(e.Exception.Message);
		}

		private void levelsDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
		{
			if (this.bindingSource1.Position < this.m_systemLevelsTotal)
			{
				this.m_systemLevelChangedFlag = 1;
				this.m_changedItemsFlag[this.bindingSource1.Position] = 1;
			}
		}

		private void okButton_Click(object sender, EventArgs e)
		{
			for (int i = 0; i < this.m_deleteExistLevelTotal; i++)
			{
				this.m_objectReference.DeleteLevel(this.m_deleteExistLevelIDValue[i]);
			}
			List<LevelsDataSource> list = new List<LevelsDataSource>();
			if (1 == this.m_systemLevelChangedFlag)
			{
				int num = 0;
				while ((long)num < this.m_changedItemsFlag.LongLength)
				{
					if (1 == this.m_changedItemsFlag[num])
					{
						this.bindingSource1.Position = num;
						LevelsDataSource levelsDataSource = this.bindingSource1.Current as LevelsDataSource;
						if (!this.m_objectReference.SetLevel(levelsDataSource.LevelIDValue, levelsDataSource.Name, levelsDataSource.Elevation))
						{
							levelsDataSource.Name = "TempName" + levelsDataSource.Name;
							list.Add(levelsDataSource);
							this.m_objectReference.SetLevel(levelsDataSource.LevelIDValue, levelsDataSource.Name, levelsDataSource.Elevation);
						}
					}
					num++;
				}
			}
			foreach (LevelsDataSource levelsDataSource2 in list)
			{
				levelsDataSource2.Name = levelsDataSource2.Name.Remove(0, 8);
				this.m_objectReference.SetLevel(levelsDataSource2.LevelIDValue, levelsDataSource2.Name, levelsDataSource2.Elevation);
			}
			for (int j = this.m_systemLevelsTotal; j < this.bindingSource1.Count; j++)
			{
				this.bindingSource1.Position = j;
				LevelsDataSource levelsDataSource3 = this.bindingSource1.Current as LevelsDataSource;
				this.m_objectReference.CreateLevel(levelsDataSource3.Name, levelsDataSource3.Elevation);
			}
			ElementId levelTypeId = this.GetLevelTypeId(this.cmbFirstType.SelectedItem.ToString());
			ElementId levelTypeId2 = this.GetLevelTypeId(this.cmbStandardType.SelectedItem.ToString());
			this.m_objectReference.ResetLevelType(levelTypeId, levelTypeId2);
			this.SaveAxisData();
		}

		private void addButton_MouseEnter(object sender, EventArgs e)
		{
			this.toolTip.Show("添加楼层", (Button)sender);
		}

		private void deleteButton_MouseEnter(object sender, EventArgs e)
		{
			this.toolTip.Show("删除楼层", (Button)sender);
		}

		public void InitFirstLevelType()
		{
			IList<Element> list = ElementFiltering.FindSpecialElements(this.m_objectReference.m_doc, typeof(LevelType), BuiltInCategory.OST_Levels);
			foreach (Element element in list)
			{
				LevelType levelType = element as LevelType;
				string name = levelType.Name;
				if (!this.cmbFirstType.Items.Contains(name))
				{
					this.cmbFirstType.Items.Add(name);
				}
			}
			if (this.cmbFirstType.Items.Count > 0)
			{
				this.cmbFirstType.SelectedIndex = 0;
			}
		}

		public void InitStandardLevelType()
		{
			IList<Element> list = ElementFiltering.FindSpecialElements(this.m_objectReference.m_doc, typeof(LevelType), BuiltInCategory.OST_Levels);
			foreach (Element element in list)
			{
				LevelType levelType = element as LevelType;
				string name = levelType.Name;
				if (!this.cmbStandardType.Items.Contains(name))
				{
					this.cmbStandardType.Items.Add(name);
				}
			}
			if (this.cmbStandardType.Items.Count > 0)
			{
				this.cmbStandardType.SelectedIndex = 0;
			}
		}

		public ElementId GetLevelTypeId(string levelTypeName)
		{
			IList<Element> list = ElementFiltering.FindSpecialElements(this.m_objectReference.m_doc, typeof(LevelType), BuiltInCategory.OST_Levels);
			foreach (Element element in list)
			{
				LevelType levelType = element as LevelType;
				string name = levelType.Name;
				if (name.Equals(levelTypeName))
				{
					return levelType.get_Parameter(BuiltInParameter.ID_PARAM).AsElementId();
				}
			}
			return null;
		}

		private void SaveAxisData()
		{
			string tempPath = Path.GetTempPath();
			string path = tempPath + "LevelSet.dat";
			FileStream fileStream = new FileStream(path, FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			streamWriter.WriteLine(this.textBoxHeight.Text);
			streamWriter.WriteLine(this.cmbFirstType.SelectedItem.ToString());
			streamWriter.WriteLine(this.cmbStandardType.SelectedItem.ToString());
			streamWriter.Flush();
			streamWriter.Close();
			fileStream.Close();
		}

		private bool ReadAxisData()
		{
			string tempPath = Path.GetTempPath();
			string path = tempPath + "LevelSet.dat";
			if (!File.Exists(path))
			{
				return false;
			}
			FileStream fileStream = new FileStream(path, FileMode.Open);
			StreamReader streamReader = new StreamReader(fileStream);
			streamReader.BaseStream.Seek(0L, SeekOrigin.Begin);
			string text = streamReader.ReadLine();
			this.textBoxHeight.Text = text;
			text = streamReader.ReadLine();
			this.cmbFirstType.SelectedItem = text;
			text = streamReader.ReadLine();
			this.cmbStandardType.SelectedItem = text;
			streamReader.Close();
			fileStream.Close();
			return true;
		}

		private void String2DistArray(string lineData, ref BindingSource bindingSource)
		{
			bindingSource.Clear();
			string[] array = lineData.Split(new char[]
			{
				'$'
			});
			foreach (string text in array)
			{
				string[] source = text.Split(new char[]
				{
					'*'
				});
				if (source.Count<string>() == 2)
				{
					LevelsDataSource levelsDataSource = new LevelsDataSource();
					levelsDataSource.Name = source.ElementAt(0);
					levelsDataSource.Elevation = Convert.ToDouble(source.ElementAt(1));
					bindingSource.Add(levelsDataSource);
				}
			}
		}

		private void levelsDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
		{
			if (this.levelsDataGridView.CurrentCell.ColumnIndex == 1)
			{
				this.EditingControl = (DataGridViewTextBoxEditingControl)e.Control;
				this.EditingControl.KeyPress += this.EditingControl_KeyPress;
				this.EditingControl.TextChanged += this.EditingControl_TextChanged;
			}
		}

		private void levelsDataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
		{
			if (e.ColumnIndex == 1)
			{
				TextBox textBox = new TextBox();
				if (this.levelsDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
				{
					textBox.Text = "";
				}
				else
				{
					textBox.Text = this.levelsDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
				}
				this.NotePastText(textBox, ref this.PastText);
			}
		}

		private void levelsDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			this.EditingControl.KeyPress -= this.EditingControl_KeyPress;
			this.EditingControl.TextChanged -= this.EditingControl_TextChanged;
			int rowIndex = e.RowIndex;
			DataGridViewCell dataGridViewCell = this.levelsDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
			if (e.ColumnIndex == 0)
			{
				string text = (string)dataGridViewCell.Value;
				if (text == null || text == "")
				{
					dataGridViewCell.Value = "临时层" + e.RowIndex.ToString();
				}
			}
		}

		private void EditingControl_TextChanged(object sender, EventArgs e)
		{
			if (this.IsNumeric(this.EditingControl.Text, true, false))
			{
				this.NotePastText(this.EditingControl, ref this.PastText);
				return;
			}
			this.RestoreText(this.EditingControl, this.PastText);
		}

		private void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
		{
			this.CheckKeyIn(e, false);
		}

		private bool IsNumeric(string NumStr, bool MayEmpty, bool ContainDot)
		{
			if ((NumStr ?? "") == "")
			{
				return MayEmpty;
			}
			if (ContainDot)
			{
				int num = NumStr.IndexOf('.');
				if (num >= 0)
				{
					num = NumStr.IndexOf('.', num + 1);
					if (num >= 0)
					{
						return false;
					}
				}
			}
			else if (NumStr.IndexOf('.') >= 0)
			{
				return false;
			}
			char[] array = NumStr.ToCharArray();
			for (int i = 0; i <= array.GetUpperBound(0); i++)
			{
				if (!char.IsDigit(array[i]))
				{
					if (array[i] != '.')
					{
						return false;
					}
					if (!ContainDot)
					{
						return false;
					}
				}
			}
			return !ContainDot || NumStr.Replace('.', '\0').Length > 0;
		}

		private void CheckKeyIn(KeyPressEventArgs Key, bool AllowDot)
		{
			if (char.IsControl(Key.KeyChar))
			{
				return;
			}
			if (char.IsDigit(Key.KeyChar))
			{
				return;
			}
			if (Key.KeyChar == '.')
			{
				if (!AllowDot)
				{
					Key.KeyChar = '\0';
				}
				return;
			}
			Key.KeyChar = '\0';
		}

		private void NotePastText(DataGridViewTextBoxEditingControl txtFrom, ref LevelsForm.struPastText NoteTo)
		{
			if (txtFrom.Text == "" || txtFrom.Text == null)
			{
				txtFrom.Text = "0";
			}
			NoteTo.Text = txtFrom.Text;
			NoteTo.SelStart = txtFrom.SelectionStart;
			NoteTo.SelLength = txtFrom.SelectionLength;
		}

		private void NotePastText(TextBox txtFrom, ref LevelsForm.struPastText NoteTo)
		{
			if (txtFrom.Text == "" || txtFrom.Text == null)
			{
				txtFrom.Text = "0";
			}
			NoteTo.Text = txtFrom.Text;
			NoteTo.SelStart = txtFrom.SelectionStart;
			NoteTo.SelLength = txtFrom.SelectionLength;
		}

		private void RestoreText(DataGridViewTextBoxEditingControl txtRestoreTo, LevelsForm.struPastText TextFrom)
		{
			txtRestoreTo.Text = TextFrom.Text;
			txtRestoreTo.SelectionStart = TextFrom.SelStart;
			txtRestoreTo.SelectionLength = TextFrom.SelLength;
		}

		private void textBoxHeight_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar != '\b' && (e.KeyChar < '0' || e.KeyChar > '9'))
			{
				e.Handled = true;
			}
		}

		private CmdLevelSet2 m_objectReference;

		private DataGridViewTextBoxEditingControl EditingControl = new DataGridViewTextBoxEditingControl();

		private int m_systemLevelsTotal;

		private int[] m_deleteExistLevelIDValue;

		private int m_deleteExistLevelTotal;

		private int[] m_changedItemsFlag;

		private int m_systemLevelChangedFlag;

		private LevelsForm.struPastText PastText = default(LevelsForm.struPastText);

		private DataGridViewTextBoxColumn LevelName;

		private DataGridViewTextBoxColumn LevelElevation;

		private struct struPastText
		{
			public struPastText(string txt, int Start, int Length)
			{
				this.Text = txt;
				this.SelStart = Start;
				this.SelLength = Length;
			}

			public string Text;

			public int SelStart;

			public int SelLength;
		}
	}
}
